package com.web.crawler.compare;

public class SimilarityCalculator {
    // 计算余弦相似度
    public static double cosineSimilarity(double[] vectorA, double[] vectorB) {
        if (vectorA.length != vectorB.length) {
            throw new IllegalArgumentException("向量必须有相同的长度");
        }

        double dotProduct = 0.0;
        double normA = 0.0;
        double normB = 0.0;

        for (int i = 0; i < vectorA.length; i++) {
            dotProduct += vectorA[i] * vectorB[i]; // 计算点积
            normA += Math.pow(vectorA[i], 2); // 计算向量A的平方和
            normB += Math.pow(vectorB[i], 2); // 计算向量B的平方和
        }

        if (normA == 0 || normB == 0) {
            return 0.0;
        }

        return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
    }

    // 计算余弦距离 (1 - 相似度)
    public static double cosineDistance(double[] vectorA, double[] vectorB) {
        return 1 - cosineSimilarity(vectorA, vectorB);
    }
}